//线上测试
export const BASE_URL = "https://qsc.exbim.com/corp/prod-api"
export const BASE_URL_CONCRETE = "https://qsc.exbim.com/concrete/prod-api"
//线上正式
// export const BASE_URL = "https://jsgl.zfcxjw.cq.gov.cn:41008/corp/prod-api"
// export const BASE_URL_CONCRETE = "https://jsgl.zfcxjw.cq.gov.cn:41008/concrete/prod-api"

export const request = {
	net(options) {
		return new Promise((resolve, reject) => {
			if( options.showLoading && options.loadingText ){  
				uni.showLoading({ title: options.loadingText })
			}
			uni.request({
				url: (options.type == 1 ? BASE_URL_CONCRETE : BASE_URL) + options.url,
				data: options.data || {},
				method: options.method||"GET",
				header: {
					"content-type": "application/json",
					"Authorization": "Bearer "+(uni.getStorageSync('token')||''),
					...options.header
				},
				success: (response) => {
					resolve(response.data);
				},
				fail: (error) => {
					reject(error);
				},
				complete: () => {
					if(options.showLoading&&options.loadingText){
						uni.hideLoading()
					}
				}
			})
		})
	},
	file(options){
		return new Promise((resolve, reject) => {
			if(options.showLoading&&options.loadingText){
				uni.showLoading({ title: options.loadingText })
			}
			uni.uploadFile({
				url: BASE_URL + options.url,
				name: "file",
				filePath: options.data.path,
				header: {
					"Accept": "application/json",
					"Authorization": "Bearer "+(uni.getStorageSync('token')||''),
					...options.header
				},
				success: (response) => {
					resolve(JSON.parse(response.data));
				},
				fail: (error) => {
					reject(JSON.parse(error));
				},
				complete: () => {
					if(options.showLoading && options.loadingText){
						uni.hideLoading()
					}
				}
			})
		})
	}
}

//拦截器
uni.addInterceptor("request", {
	//请求前
	invoke(args) {
	
	},
	//请求后
	success(res) {
		//判断是否为文件流
		if (res.data instanceof ArrayBuffer) {
			return res;
		}
		res.data.message = res.data.msg || res.data.message || 'Error'
		// 拦截器
		if(res.data.code != 200 && ![0,1,100].includes(res.data.code)){
			if (res.data.code == 401) {
				uni.showToast({ title: "登录已过期", icon: "none"})
				setTimeout(()=>{
					uni.removeStorageSync("token")
					uni.removeStorageSync("phone")
					uni.removeStorageSync('userInfo')
					// uni.removeStorageSync('role')
					uni.removeStorageSync('activeProject')
					uni.removeStorageSync('authCode')
					uni.reLaunch({
						url: "/pages/login/index"
					})
				}, 500)
			} else {
				uni.hideLoading()
				uni.showModal({
					showCancel: false,
					content: res.data.message
				})
			}
		}
	},
	fail(err) {
		uni.hideLoading()
		uni.showModal({
			showCancel: false,
			content: "请求超时, 请检查网络"
		})
	}
});
